package com.example.demo.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.BookMapper;
import com.example.demo.pojo.Book;
import com.example.demo.service.BookService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;


/**
 * (SBook)表服务实现类
 *
 * @author makejava
 * @since 2023-05-20 10:12:38
 */
@Service("bookService")
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
	@Resource
	BookMapper bookMapper;

	@Override
	public HashMap<String, Long> radarMapList() {

		//获取每个书籍类型的销量总数，以书籍类型进行分组
		List<Book> list = baseMapper.selectList(null);
		Map<String, List<Book>> collect =
				list.stream().collect(Collectors.groupingBy(Book::getType));

		HashMap<String, Long> hashMap = new HashMap<>();
		collect.forEach((key, value) -> {
			//获取每一个书籍类型的销量总和
			long sum = value.stream().mapToLong(Book::getSales).sum();
			hashMap.put(key,sum);
		});
		return hashMap;
	}

	@Override
	public List<List<Object>> getScatterDiagram() {
		//从数据库获取前100条数据（只获取Sales和价格price）
		List<Book> list =baseMapper.selectList(new LambdaQueryWrapper<Book>()
				.select(Book::getSales,Book::getPrice).last("limit 100"));

		//对一百条数据做成[[],[]]类型的数据返回前端
		return list.stream().map(item -> {
			ArrayList<Object> objects1 = new ArrayList<>();
			objects1.add(item.getSales());
			//对价格处理去除￥
			objects1.add(Float.parseFloat(item.getPrice().replaceAll("￥ ","").trim()));
			//返回
			return new ArrayList<>(objects1);
		}).collect(Collectors.toList());
	}

	/**
	 * 数据获取
	 * @throws IOException
	 */
	@Override
	public void getBooks() throws IOException {
		{
			for (int i = 1; i < 6; i++) {
				List<Book> booksList = new ArrayList<>();
				String urls = "https://search.xhsd.com/search?frontCategoryId=38&pageNo=" + i;
				final Document parse = Jsoup.parse(new URL(urls), 5000);
				Elements li = parse.getElementsByTag("li");
				for (Element element : li) {
					Elements elementsByClass = element.getElementsByClass("product js-product ");
					if (!elementsByClass.isEmpty()) {
						Book books=new Book();
						String p = element.getElementsByTag("p").text();
						//书名
						String bookName = element.getElementsByTag("p").eq(0).text();
						System.out.println("书名:" + bookName);
						books.setName(bookName);
						//作者
						String author = element.getElementsByTag("p").eq(1).text();
						System.out.println("作者:" + author);
						books.setAuthor(author);
						//价格
						String price = element.getElementsByTag("p").eq(2).text();
						System.out.println("价格:" + price);
						books.setPrice(price);
						//
						String img = element.getElementsByTag("img").attr("src");
						System.out.println("图片：" + "http:" + img);
						books.setImgurl("http:" + img);
						Long substring = Long.valueOf(UUID.randomUUID()
								.toString()
								.replaceAll("[^1-9]", "").substring(0, new Random().nextInt(4) + 1));
						books.setSales(substring);
						System.out.println("销售量：" + substring);
						//人文艺术，人文社科，少儿童书，教育考试，经济金融，生活休闲
						books.setType("人文艺术");
						booksList.add(books);
					}
				}
				booksList.forEach(item -> {
					bookMapper.insert(item);
				});
			}
		}
	}

}
